package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.NonStaticResourceHttpRequestHandler;
import com.alvis.media.base.RestResponse;
import com.alvis.media.constant.VideoInfoConstant;
import com.alvis.media.domain.User;
import com.alvis.media.domain.VideoInfo;
import com.alvis.media.service.VideoInfoService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.video.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@RestController("AdminVideoController")
@RequestMapping(value = "/api/admin/videos")
@AllArgsConstructor
public class VideoController  extends BaseApiController
{
    // DI/IoC
    @Autowired
    private VideoInfoService videoInfoService;

    @Autowired
    private NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 视频播放
     */
    @GetMapping("/play/**/*")
    public void playVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //realPath 即视频所在的完整地址
        String url = request.getRequestURL().toString();
        int index=  url.lastIndexOf("D:");
        String realPath = url.substring(index);

        Path filePath = Paths.get(realPath);
        if (Files.exists(filePath)) {
            // 利用 Files.probeContentType 获取文件类型
            String mimeType = Files.probeContentType(filePath);
            if (!StringUtils.isEmpty(mimeType)) {
                // 设置 response
                response.setContentType(mimeType);
            }
            request.setAttribute(nonStaticResourceHttpRequestHandler.filepath, filePath);
            // 利用 ResourceHttpRequestHandler.handlerRequest() 实现返回视频流
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }

    /**
     * 视频列表
     */
    @RequestMapping(value = "/admin/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo <VideoResponseVM>> pageList(@RequestBody VideoPageRequestVM model)
    {
        // 光标放在要自动添加返回值类型的方法的最前面,然后Alt+Enter --> introduce local variable --> 自动导入这个方法的返回值类型
        PageInfo<VideoInfo> videoPageInfo = videoInfoService.videoPage(model);

        // 将PageInfo<User> userPageInfo类型 --> PageInfo<UserResponseVM>类型
        PageInfo<VideoResponseVM> videoResponseVM = PageInfoHelper.copyMap(videoPageInfo, (d) -> VideoResponseVM.from(d));
        return RestResponse.ok(videoResponseVM);
    }


    /**
     * 添加视频
     */
    @RequestMapping(value = "/admin/create", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> createVideo(@RequestBody @Valid VideoCreateVM model)
    {
        VideoInfo videoInfo = modelMapper.map(model, VideoInfo.class);

        String videoURL = model.getVideoUrl();
        // 校验用户是否上传视频，如果未上传，则给用户提示“视频文件未上传”
        if (StringUtils.isBlank(videoURL))  // 立即结束程序return
        {
            return RestResponse.fail(VideoInfoConstant.VIDEO_FILE_NOT_UPLOADED,"视频文件未上传");
        }

        if (model.getVideoCategory() == null)
        {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NAME_IS_CATEGORY,"视频文件未上传");
        }

        if (model.getVideoName() == null)
        {
            return RestResponse.fail(VideoInfoConstant.VIDEO_NAME_IS_NULL,"视频名称为NULL了");
        }

        User currentUser = getCurrentUser();  // 获取当前登录的用户

        videoInfo.setCreatorId(currentUser.getId()); // 视频的创建者的编号
        videoInfo.setVideoCategory(model.getVideoCategory()); // 设置视频分类
        videoInfo.setVideoName(model.getVideoName()); // 设置视频名称
        videoInfo.setCreateTime(new Date());
        String newVideoUrl = DateTimeUtil.getCurrentTimeYMD() + StringUtils.substring(videoURL, StringUtils.lastIndexOf(videoURL,"/"));
        videoInfo.setVideoUrl(newVideoUrl);
        videoInfoService.insertByFilter(videoInfo); // 调用service层做入库操作
        return RestResponse.ok();
    }

    @RequestMapping(value = "/admin/select/{id}", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> select(@PathVariable Integer id) {

        return null;
    }

    @RequestMapping(value = "/admin/getVideoDetailByVideoId/{id}", method = RequestMethod.POST)
    public RestResponse <VideoDetailVM> getVideoDetailByVideoId(@PathVariable Integer id) {

        return null;
    }


    @RequestMapping(value = "/admin/edit", method = RequestMethod.POST)
    public RestResponse<VideoResponseVM> editVideo(@RequestBody @Valid VideoCreateVM model) {
        return RestResponse.ok();
    }

    @RequestMapping(value = "/admin/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        return RestResponse.ok();
    }


    @RequestMapping(value = "/admin/userAnalysis/{id}", method = RequestMethod.POST)
    public RestResponse <UserAnalysisVM> userAnalysis(@PathVariable Integer id) {

        UserAnalysisVM vm = new UserAnalysisVM();

        return RestResponse.ok(vm);

    }
}

